using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AutoGear.BLL;
using ECommerce.Library.DataStructure;
using ECommerce.Library;
using System.Collections.Generic;
using ECommerce.Library.Web;



public partial class myaccount_order_status : SitePublicBasePage
{
    private int _pageSize = 0;
    private int _totalItem = 0;
    private int _currentPageIndex = 0;
    private int _totalPage = 0;
    private bool _isLastPage = false;
    private bool _isFirstPage = false;
    private DateTime _searchDateFrom;
    private DateTime _searchDateTo;
    private double _searchPriceFrom = 0.0;
    private double _searchPriceTo = 0.0;
    private string _searchLastName = string.Empty;
    private string _searchEmail = string.Empty;
    private string _sortBy = string.Empty;
    private bool _showAllPage = false;
    private bool _useSearch = false;

    private ProductPurchaseOrder Order;
  
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (SessionManager.IsUserLoggedIn)
            {
                GenerateSEOData();
                this._currentPageIndex = 1;
                LoadData();
                SetPageTitleAndBreadcramb();
            }
            else
            {
                Response.Redirect(string.IsNullOrEmpty(SupplierId) ? CustomSiteMap.Login : "~/partner/" + SupplierId + "/login.aspx");
            }
        }
    }

    private void SetPageTitleAndBreadcramb()
    {
        ContentPlaceHolder ph = (ContentPlaceHolder)this.Master.Master.FindControl("cphMiddleContent");

        Literal litPageTitle = (Literal)ph.FindControl("litPageTitle");
        Literal litCurrentPage = (Literal)ph.FindControl("litCurrentPage");

        if (litPageTitle != null)
        {
            litCurrentPage.Text = litPageTitle.Text = "Order Status";

        }
    }

    private void GenerateSEOData()
    {
        //SEOHelper.RenderTitle(this.Page, "Order Status :: Traditional Polish foods, steaks, Polish sausages, Polish dumplings, Polish pastries, Polish soups, Polish stews by Polana", true);
        //SEOHelper.RenderMetaTag(this.Page, "description", "Authentic, traditional Polish sausages, kielbasa, smoked sausages, bacon, blood sausage, steaks, premade dishes, parties, torts, breads, coffees, teas, canned goods, dry goods, recipes and more from Polana.", true);
        //SEOHelper.RenderMetaTag(this.Page, "keywords", "authentic, traditional, kielbasa, buy polish food, order polish food, dumplings, coffee, tea, cookies, chocolates, pastries, torts, soups, stews, European sausage, fresh polish sausage, smoked sausage, polish food, polish recipes, polish hams, polish bacons, fresh sausage, sausages, deli sausage, smoked sausages, blood sausages, headcheese, polish cheese, polish hams, polish blood sausage, polish bacon, wienners", true);
        SEOHelper.RenderMetaTag(this.Page, "robots", "ALL", true);
    }

    private void ReadPagingData()
    {
        this._pageSize = Convert.ToInt32(ViewState["Page_Size"]);
        this._totalItem = Convert.ToInt32(ViewState["Total_Item"]);
        this._currentPageIndex = Convert.ToInt32(ViewState["Current_Page_Index"]);
        this._totalPage = Convert.ToInt32(ViewState["Total_Page"]);
        this._isLastPage = Convert.ToBoolean(ViewState["Is_Last_Page"]);
        this._isFirstPage = Convert.ToBoolean(ViewState["Is_First_Page"]);
        this._searchDateFrom = Convert.ToDateTime(ViewState["Search_DateFrom"]);
        this._searchDateTo = Convert.ToDateTime(ViewState["Search_DateTo"]);
        this._searchPriceFrom = Convert.ToDouble(ViewState["Search_PriceFrom"]);
        this._searchPriceTo = Convert.ToDouble(ViewState["Search_PriceTo"]);
        this._searchLastName = Convert.ToString(ViewState["Search_LastName"]);
        this._searchEmail = Convert.ToString(ViewState["Search_Email"]);
        this._sortBy = Convert.ToString(ViewState["Sort_By"]);
        this._showAllPage = Convert.ToBoolean(ViewState["Show_All_Page"]);
        this._useSearch = Convert.ToBoolean(ViewState["Use_Search"]);
    }

    private void WritePagingData()
    {
        ViewState["Page_Size"] = this._pageSize;
        ViewState["Total_Item"] = this._totalItem;
        ViewState["Current_Page_Index"] = this._currentPageIndex;
        ViewState["Total_Page"] = this._totalPage;
        ViewState["Is_Last_Page"] = this._isLastPage;
        ViewState["Is_First_Page"] = this._isFirstPage;
        ViewState["Search_DateFrom"] = this._searchDateFrom;
        ViewState["Search_DateTo"] = this._searchDateTo;
        ViewState["Search_PriceFrom"] = this._searchPriceFrom;
        ViewState["Search_PriceTo"] = this._searchPriceTo;
        ViewState["Search_LastName"] = this._searchLastName;
        ViewState["Search_Email"] = this._searchEmail;
        ViewState["Sort_By"] = this._sortBy;
        ViewState["Show_All_Page"] = this._showAllPage;
        ViewState["Use_Search"] = this._useSearch;
    }

    private ReadWriteCustomCollection<ProductPurchaseOrder> FetchData()
    {
        const int SHOW_ALL_COUNT = 999999;
        ReadWriteCustomCollection<ProductPurchaseOrder> data = null;
        int firstItem = (this._currentPageIndex - 1) * this._pageSize;
        int pageSize = this._showAllPage ? SHOW_ALL_COUNT : this._pageSize;
        try
        {
           data = ProductPurchaseOrder.GetProductPurchaseOrderByUserId(SessionManager.LoggedUser.UserId, this._sortBy, firstItem, pageSize);
           
        }
        catch (Exception ex) { 
        
        }        

        return data;
    }

    private int GetTotalItemCount()
    {
        int totalItemCount = 0;
        try
        {
            totalItemCount = ProductPurchaseOrder.GetProductPurchaseOrderByUserIdCount(SessionManager.LoggedUser.UserId);
        }
        catch (Exception ex)
        {

        }
        return totalItemCount;
    }

    private void BindGrid()
    {
        try
        {
            ReadPagingData();


            ReadWriteCustomCollection<ProductPurchaseOrder> productPurchaseOrder = FetchData();

            int firstItemPosition = (this._currentPageIndex - 1) * this._pageSize;
            int lastItemPosition = this._currentPageIndex * this._pageSize - 1;

            this._totalItem = GetTotalItemCount();
            this._totalPage = (int)Math.Ceiling(this._totalItem / (double)this._pageSize);

            if (this._showAllPage || lastItemPosition >= this._totalItem)
                lastItemPosition = this._totalItem - 1;

            grvProductPurchaseOrder.DataSource = productPurchaseOrder;
            grvProductPurchaseOrder.DataBind();

            lblFirstItemNumber.Text = this._totalItem == 0 ? "0" : (firstItemPosition + 1).ToString();
            lblLastItemNumber.Text = (lastItemPosition + 1).ToString();
            lblTotalItem.Text = this._totalItem.ToString();

            BindPager();
        }
        catch (Exception ex)
        {

        }
    }

    private void LoadData()
    {
        this._pageSize = SiteUtility.GridDefaultPageSize;
        this._totalItem = GetTotalItemCount();
        this._currentPageIndex = 1;
        this._totalPage = (int)Math.Ceiling(this._totalItem / (double)this._pageSize);
        this._isLastPage = IsLastPage();
        this._isFirstPage = IsFirstPage();
        this._sortBy = "CreateDate DESC";
        this._showAllPage = false;
        this._useSearch = false;

        WritePagingData();
        BindGrid();
    }

    protected void Paging_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "paging")
        {
            ReadPagingData();

            if (Convert.ToString(e.CommandArgument) == "All")
            {
                this._currentPageIndex = 1;
                this._showAllPage = true;
            }
            else
            {
                int currentPage = Convert.ToInt32(e.CommandArgument);
                this._currentPageIndex = currentPage;
                this._showAllPage = false;
            }
            grvProductPurchaseOrder.EditIndex = -1;
            WritePagingData();
            BindGrid();
        }
    }

    protected void Grid_Sort(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "sort")
        {
            grvProductPurchaseOrder.EditIndex = -1;
            ReadPagingData();
            this._sortBy = (string)e.CommandArgument;
            if (this._sortBy.Contains("DisplayOrder"))
            {
                this._sortBy = this._sortBy.Replace("DisplayOrder", "CONVERT(int,DisplayOrder)");
            }
            WritePagingData();
            BindGrid();
        }
    }

    protected void ProductPurchaseOrder_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal
            || e.Row.RowState == DataControlRowState.Alternate))
        {
            HiddenField hdfOrderId = (HiddenField)e.Row.FindControl("hdfProductPurchaseOrderId");
            if (hdfOrderId != null)
            {
                ProductPurchaseOrder product = ProductPurchaseOrder.Load(int.Parse(hdfOrderId.Value));
                if (product != null)
                {
                    Label lblOrderStatus = (Label)e.Row.FindControl("lblOrderStatus");
                    Label lblTrackingNo = (Label)e.Row.FindControl("lblTrackingNo");
                    if (!string.IsNullOrEmpty(product.OrderTrackNumber))
                    {
                        lblTrackingNo.Text = product.OrderTrackNumber;
                    }
                    else 
                    {
                        lblTrackingNo.Text = string.Empty;
                    }
                    string status=string.Empty;
                    if (product.OrderStatus == OrderStatus.CCSuccess || product.OrderStatus == OrderStatus.ManualAuthorization)
                    {
                        lblOrderStatus.Text = "Success";
                        lblOrderStatus.Style.Add("Color","Green");
                    }
                    else 
                    {
                        lblOrderStatus.Text = "Fail";
                        lblOrderStatus.Style.Add("Color", "Red");
                    }
                }
            }
        }

    }

    protected void NavigateToEditPage(object sender, CommandEventArgs e)
    {
        //Response.Redirect(CustomSiteMap.ProductPurchaseOrderEdit + "?cid=" + e.CommandArgument);
        string orderNumber = e.CommandArgument.ToString();
        AutoGearSessionManager.OrderNumber = orderNumber;
        string popupScript = "<script> window.open(\"" + Page.ResolveUrl(CustomSiteMap.InvoicePrintPage) + "?print=0\",\"popUpWindow\")</script>";
        ClientScript.RegisterClientScriptBlock(this.GetType(), "popup", popupScript);

    }
    protected void NavigateToShoppingCart(object sender, CommandEventArgs e)
    {
        string orderNumber = e.CommandArgument.ToString();
        Order = new ProductPurchaseOrder(orderNumber,true);
        AutoGearSessionManager.ShoppingCart = Order.ShoppingCart;
        Response.Redirect(CustomSiteMap.ShoppingCart);
    }  
    private void BindPager()
    {
        List<string> pages = new List<string>();
        for (int i = 1; i <= this._totalPage; i++)
            pages.Add(i.ToString());

        rptPaging.DataSource = pages;
        rptPaging.DataBind();
    }

    private bool IsFirstPage()
    {
        if (this._currentPageIndex == 1)
            return true;
        else
            return false;
    }

    private bool IsLastPage()
    {
        if (this._currentPageIndex == this._totalPage)
            return true;
        else
            return false;
    }

    private int FindDataIndex(string dataId)
    {
        foreach (GridViewRow row in grvProductPurchaseOrder.Rows)
        {
            HiddenField hdfProductPurchaseOrderId = (HiddenField)row.FindControl("hdfProductPurchaseOrderId");
            if (hdfProductPurchaseOrderId != null && hdfProductPurchaseOrderId.Value == dataId)
            {
                return row.RowIndex;
            }
        }
        return -1;
    }



}


